#!/usr/bin/env node
/**
 * 修复 vip_claim_records 表中 type=4（国土特权）且 pid=0 的历史数据，
 * 将其回填为对应 vip_reward_config（type=4, status=1）的配置主键 id，
 * 以实现“各 VIP 等级各领一次”的正确去重。
 *
 * 依赖环境变量（从 .env 读取）：
 * - DB_HOST / MYSQL_HOST
 * - DB_PORT / MYSQL_PORT
 * - DB_USERNAME / MYSQL_USER / DB_USER
 * - DB_PASSWORD / MYSQL_PASSWORD / DB_PASS
 * - DB_DATABASE / MYSQL_DATABASE / DB_NAME
 *
 * 使用：
 *   node scripts/fix-vip-claim-pid.js --dry-run   仅预览将更新的行数
 *   node scripts/fix-vip-claim-pid.js             执行修复并输出影响行数
 */

/* eslint-disable no-console */
const fs = require('fs');
const path = require('path');

// 加载 .env（若存在）
try {
    const dotenvPath = path.resolve(process.cwd(), '.env');
    if (fs.existsSync(dotenvPath)) {
        require('dotenv').config({ path: dotenvPath });
    }
} catch (_) { }

async function main() {
    const isDryRun = process.argv.includes('--dry-run');

    // 读取连接信息（多别名兼容）
    const host = process.env.DB_HOST || process.env.MYSQL_HOST || '127.0.0.1';
    const port = Number(process.env.DB_PORT || process.env.MYSQL_PORT || 3306);
    const user = process.env.DB_USERNAME || process.env.MYSQL_USER || process.env.DB_USER || 'root';
    const password = process.env.DB_PASSWORD || process.env.MYSQL_PASSWORD || process.env.DB_PASS || '';
    const database = process.env.DB_DATABASE || process.env.MYSQL_DATABASE || process.env.DB_NAME || '';

    if (!database) {
        console.error('[fix-vip-claim-pid] 未配置数据库名（DB_DATABASE / MYSQL_DATABASE / DB_NAME）');
        process.exit(2);
    }

    let mysql;
    try {
        mysql = require('mysql2/promise');
    } catch (e) {
        console.error('[fix-vip-claim-pid] 缺少依赖 mysql2，请先安装：npm i mysql2');
        process.exit(2);
    }

    const conn = await mysql.createConnection({ host, port, user, password, database, multipleStatements: true });
    try {
        // 确保表存在
        await conn.query(
            'CREATE TABLE IF NOT EXISTS vip_claim_records (\n' +
            '  id INT NOT NULL AUTO_INCREMENT,\n' +
            '  characterId INT NOT NULL,\n' +
            '  lvl INT NOT NULL,\n' +
            '  pid INT NOT NULL,\n' +
            '  type INT NOT NULL,\n' +
            '  claimed_at DATETIME NOT NULL,\n' +
            '  PRIMARY KEY (id),\n' +
            '  UNIQUE KEY uniq_claim (characterId,lvl,pid,type)\n' +
            ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'
        );

        // 预览将受影响的行
        const [previewRows] = await conn.query(
            `SELECT COUNT(1) AS cnt\n` +
            `FROM vip_claim_records c\n` +
            `JOIN vip_reward_config v\n` +
            `  ON v.vip_level = c.lvl AND v.type = 4 AND v.status = 1\n` +
            `WHERE c.type = 4 AND c.pid = 0`
        );
        const willAffect = Number(previewRows?.[0]?.cnt || 0);

        if (isDryRun) {
            console.log(`[fix-vip-claim-pid] 预览：将更新 ${willAffect} 行 (type=4, pid=0)`);
            return;
        }

        // 执行修复：按 lvl 映射 pid 为 vip_reward_config.id
        const [res] = await conn.query(
            `UPDATE vip_claim_records c\n` +
            `JOIN vip_reward_config v\n` +
            `  ON v.vip_level = c.lvl AND v.type = 4 AND v.status = 1\n` +
            `SET c.pid = v.id\n` +
            `WHERE c.type = 4 AND c.pid = 0`
        );

        // 统计修复后的异常（若仍存在 pid=0）
        const [afterRows] = await conn.query(
            `SELECT COUNT(1) AS cnt FROM vip_claim_records WHERE type = 4 AND pid = 0`
        );
        const remain = Number(afterRows?.[0]?.cnt || 0);

        const affected = Number(res?.affectedRows || 0);
        console.log(`[fix-vip-claim-pid] 已修复 ${affected} 行，剩余 pid=0 的国土记录：${remain}`);
    } finally {
        try { await conn.end(); } catch (_) { }
    }
}

main().catch((err) => {
    console.error('[fix-vip-claim-pid] 执行失败：', err?.message || err);
    process.exit(1);
});


